<template>
  <div class="menu-content-attribute-version">
    <a-button @click="layoutGraph" class="button-layout-graph">
      重置视角
    </a-button>
    <div class="select-zoom">
      <select-zoom v-model:zoom="zoom" :graph="graph" />
    </div>
    <div class="icon-zoom-in">
      <icon-zoom-in v-model:zoom="zoom" :graph="graph" />
    </div>
    <div class="icon-zoom-out">
      <icon-zoom-out v-model:zoom="zoom" :graph="graph" />
    </div>
    <a-spin :spinning="loading" v-if="loading" />
    <div class="container" id="container" v-else></div>
  </div>
</template>
<script setup>
import { nextTick, onMounted, onUnmounted, ref, shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Graph } from '@antv/g6'
import { message } from 'ant-design-vue'
import SelectZoom from './menu-content-attribute-version-zoom-select.vue'
import IconZoomIn from './menu-content-attribute-version-zoom-in.vue'
import IconZoomOut from './menu-content-attribute-version-zoom-out.vue'

import mockAPI from '@/api/simple-mock.js'
import { downloadFile, getVersionView, versionBack } from '@/api/db.js'
import { downloadFormBlob } from '@/utils/util.js'
import { useDbType } from '@/views/db-management/provide-context.js'
import useKeepAliveStore from '@/stores/keep-alive.js'
/**
 * 事件
 */
let emit = defineEmits(['update'])
/**
 * 全局
 */
let router = useRouter()
let route = useRoute()
let keepAliveStore = useKeepAliveStore()
/**
 * 加载数据
 */
let loading = ref(false)
let activeVersion = ref()
let dbType = useDbType()
onMounted(async () => {
  loading.value = true
  try {
    let result = await getVersionView({ fileId: route?.params?.fileid }, dbType)
    let options = standardisation(result.data)
    nextTick(() => {
      render(options)
    })
  } catch (e) {}
  loading.value = false
})
function standardisation(data = []) {
  let nodeMap = {}
  let edgeMap = {}
  data.forEach(item => {
    let {
      id,
      fileName,
      fileVersion,
      preVersion,
      fileCode,
      effectFlag,
      parentId,
    } = item
    if (fileVersion) {
      fileVersion = fileVersion.toString()
    }
    if (preVersion) {
      preVersion = preVersion.toString()
    }
    if (effectFlag) {
      activeVersion.value = fileVersion
    }
    nodeMap[fileVersion] = {
      id: fileVersion,
      data: {
        dataId: id,
        fileCode,
        dataName: fileName,
        version: fileVersion,
        effectFlag,
        categoryId: parentId,
      },
    }
    if (preVersion && fileVersion) {
      edgeMap[id] = {
        id,
        source: preVersion,
        style: { labelText: '' },
        target: fileVersion,
      }
    }
  })
  return {
    nodes: Object.values(nodeMap),
    edges: Object.values(edgeMap),
  }
}

/**
 * 图
 */
let zoom = ref(1)
/**
 * 创建图
 */
let saltOption = parseInt(Math.random() * 100000000)
let graph = shallowRef()
function render(data) {
  graph.value = new Graph({
    container: 'container',
    autoFit: 'view',
    data,
    node: {
      type: 'html',
      style: {
        size: [220, 88],
        // dx: -120,
        // dy: -40,
        innerHTML: params => {
          let salt = parseInt(Math.random() * 10000000)
          let dropdownOptionsId = `options-${salt}`
          let dropdownButtonId = `button-${salt}`
          let linkElement = params.data.effectFlag
            ? `
          <div
            style="
              font-size: 14px;
              color: rgba(0, 0, 0, 0.85);
              line-height: 32px;
              cursor: pointer;
              padding: 0px 5px;
            "
            onMouseOver="this.style.background='#f7f7f7'"
            onMouseOut="this.style.background='#ffffff'"
            class="link-${saltOption}"
            data-id="${params.data.dataId}"
            data-name="${params.data.dataName}"
            data-category-id="${params.data.categoryId}"
            data-version="${params.data.version}"
          >
            跳转路径
          </div>
          `
            : `
          <div
            style="
              font-size: 14px;
              color:#ccc;
              line-height: 32px;
              cursor: pointer;
              padding: 0px 5px;
              cursor: no-drop;
            "
          >
            跳转路径
          </div>`
          let backElement = params.data.effectFlag
            ? `
          <div
            style="
              font-size: 14px;
              color:#ccc;
              line-height: 32px;
              cursor: pointer;
              padding: 0px 5px;
              cursor: no-drop;
            "
          >
            回退至当前版本
          </div>`
            : `
          <div
            style="
              font-size: 14px;
              color: rgba(0, 0, 0, 0.85);
              line-height: 32px;
              cursor: pointer;
              padding: 0px 5px;
            "
            onMouseOver="this.style.background='#f7f7f7'"
            onMouseOut="this.style.background='#ffffff'"
            class="back-${saltOption}"
            data-id="${params.data.dataId}"
            data-name="${params.data.dataName}"
            data-category-id="${params.data.categoryId}"
            data-version="${params.data.version}"
          >
            回退至当前版本
          </div>`

          return `
              <div
                style="
                  width:100%;
                  height: 100%;
                  background:${params.data.effectFlag ? '#eff4ff' : '#fcfcfc'};
                  border: ${params.data.effectFlag ? '1px solid #dbe3f9' : '1px solid #ececec'};
                  border-radius: 2px;
                  box-shadow: 1px 2px 5px 0 rgba(0,0,0,0.05);
                  padding: 8px;
                  box-sizing: border-box;
                "
              >
                <style>
                  #${dropdownButtonId}:hover #${dropdownOptionsId}{
                    display: block !important;
                  }
                </style>
                <table style="font-size: 12px;color: rgba(0, 0, 0, 0.85); width:100%; white-space: nowrap;">
                  <tbody>
                    <tr>
                      <td class="col1">
                        文件名:&nbsp;&nbsp;${params.data.dataName}
                      </td>
                      <td class="col2" style="width:25px">
                        <div style="position: relative" id="${dropdownButtonId}" >
                          <svg class="icon" style="color: #bfbfbf; font-size: 20px; margin-left: 5px; cursor: pointer; width: 1em;height: 1em;vertical-align: -0.15em;fill: currentColor;overflow: hidden; pointer-events: all;">
                            <use xlink:href="#icon-gengduo-shuxiang"></use>
                          </svg>
                          <div
                            style="
                              position: absolute;
                              top: 30px;
                              right: -10px;
                              background: #ffffff;
                              box-shadow:
                                0 6px 16px 0 rgba(0, 0, 0, 0.08),
                                0 3px 6px -4px rgba(0, 0, 0, 0.12),
                                0 9px 28px 8px rgba(0, 0, 0, 0.05);
                              padding: 6px 5px;
                              white-space: nowrap;
                              display: none;
                            "
                            id="${dropdownOptionsId}"
                          >
                            <div
                              style="
                                width: 0;
                                height: 0;
                                border-left: 10px solid transparent;
                                border-right: 10px solid transparent;
                                border-bottom: 10px solid #fff;
                                position: absolute;
                                top: -10px;
                                right: 10px;
                              "
                            ></div>
                            <div
                              style="
                                font-size: 14px;
                                color: rgba(0, 0, 0, 0.85);
                                line-height: 32px;
                                cursor: pointer;
                                padding: 0px 5px;
                              "
                              onMouseOver="this.style.background='#f7f7f7'"
                              onMouseOut="this.style.background='#ffffff'"
                              class="download-${saltOption}"
                              data-id="${params.data.dataId}"
                              data-name="${params.data.dataName}"
                              data-category-id="${params.data.categoryId}"
                              data-version="${params.data.version}"
                            >
                              下载
                            </div>
                            ${linkElement}
                            ${backElement}
                          </div>
                        </div>
                      </td>
                    </tr>
                    <tr>
                      <td class="col1" colspan="2">编号:&nbsp;&nbsp;${params.data.fileCode}</td>
                    </tr>
                    <tr>
                      <td class="col1" colspan="2">版本号:&nbsp;&nbsp;${params.data.version}</td>
                    </tr>
                  </tbody>
                </table>
              </div>`
        },
      },
    },
    edge: {
      type: 'polyline',
      style: {
        router: {
          type: 'orth',
        },
        endArrow: true,
        startArrowSize: 20,
        stroke: '#c2c8d5',
        // labelText: params => params.data.text,
        labelFill: '#0086ff',
        labelAutoRotate: false,
      },
      // style: {
      //   endArrow: true,
      //   startArrowSize: 20,
      // },
    },
    layout: {
      type: 'dendrogram',
      direction: 'LR', // H / V / LR / RL / TB / BT
      nodeSep: 140,
      rankSep: 260,
      // radial: true,
    },
    behaviors: [
      'drag-canvas',
      'zoom-canvas',
      'drag-element',
      'collapse-expand',
    ],
  })
  graph.value.render()
  setTimeout(() => {
    layoutGraph()
  })
}

/**
 *重置
 */
function layoutGraph() {
  if (activeVersion.value) {
    graph.value.focusElement(activeVersion.value)
  }
  zoom.value = graph.value.getZoom()
}
/**
 * 绑定操作事件
 */
function download(event) {
  if (event.target.className === `download-${saltOption}`) {
    let dataId = event.target.getAttribute('data-id')
    downloadFile({ fileId: dataId }, dbType)
      .then(downloadFormBlob)
      .catch(() => {
        message.error(`下载失败<${dataId}>`)
      })
  }
}
function link(event) {
  if (event.target.className === `link-${saltOption}`) {
    let dataname = event.target.getAttribute('data-name')
    let categoryid = event.target.getAttribute('data-category-id')

    keepAliveStore.clearInclude()
    router.push({
      path: dbType
        ? `/private/db-management/${dbType}`
        : '/private/db-management/project',
      query: { dataname, categoryid },
    })
  }
}
async function back(event) {
  if (event.target.className === `back-${saltOption}`) {
    let button = event.target
    let dataId = event.target.getAttribute('data-id')
    let version = event.target.getAttribute('data-version')
    let categoryId = event.target.getAttribute('data-category-id')
    button.style.color = '#ccc'
    button.style.pointerEvents = 'none'
    button.style.cursor = 'no-drop'
    try {
      await versionBack(
        {
          fileId: route?.params?.fileid,
          targetVersion: version,
        },
        dbType,
      )
      if (dbType) {
        router.replace({
          path: `/private/db-management-preview-${dbType}/${categoryId}/${dataId}/${route?.params?.fileid}`, //:id/:fileid
        })
      } else {
        router.replace({
          path: `/private/db-management-preview/${categoryId}/${dataId}/${route?.params?.fileid}`, //:id/:fileid
        })
      }
      emit('update')
    } catch (e) {
      console.log(e)
    }
    button.style.color = '#000'
    button.style.pointerEvents = 'all'
    button.style.cursor = 'pointer'
  }
}
onMounted(() => {
  document.addEventListener('click', download)
  document.addEventListener('click', link)
  document.addEventListener('click', back)
})
onUnmounted(() => {
  document.removeEventListener('click', download)
  document.removeEventListener('click', link)
  document.removeEventListener('click', back)
})
</script>
<style lang="less" scoped>
.menu-content-attribute-version {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .button-layout-graph {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }
  .select-zoom {
    position: absolute;
    top: 5px;
    right: 70px;
    z-index: 1;
  }
  .icon-zoom-in {
    position: absolute;
    top: 12px;
    right: 0;
    z-index: 1;
  }
  .icon-zoom-out {
    position: absolute;
    top: 12px;
    right: 36px;
    z-index: 1;
  }
  .container {
    width: 100%;
    height: 100%;
  }
}
</style>
